import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_app/routes/routes.dart';
import 'package:flutter_app/utils/dio_http.dart';
import 'package:flutter_app/utils/utils.dart';
import 'package:flutter_app/widgets/toast_common.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({Key? key}) : super(key: key);

  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final TextEditingController _userNameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _repeatPasswordController =
      TextEditingController();

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  // 显示/隐藏密码
  bool _showPassword = true;
  void _changeIcon() {
    setState(() {
      _showPassword = !_showPassword;
    });
  }

  _submitRegister() async {
    var username = _userNameController.text;
    var password = _passwordController.text;
    var repeatPassword = _repeatPasswordController.text;
    if (password != repeatPassword) {
      ToastCommon.showToast('两次密码不一致！');
    }
    if (verifyIsEmpty(username) || verifyIsEmpty(password)) {
      ToastCommon.showToast('用户名或密码不能为空！');
    }
    var params = {"username": username, "password": password};
    var res = await DioHttp.of(context).post('/user/registered', params);
    var resString = json.decode(res.toString());
    int status = resString["status"];
    String desc = resString["description"] ?? "内部错误";
    ToastCommon.showToast(desc);
    if (status.toString().startsWith('2')) {
      Navigator.pushReplacementNamed(context, '/login');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('注册'),
        ),
        body: Padding(
            padding: const EdgeInsets.all(20),
            child: Form(
                autovalidateMode:
                    AutovalidateMode.onUserInteraction, //设置validator时自动验证
                key: _formKey,
                child: Column(
                  children: [
                    TextFormField(
                      controller: _userNameController,
                      decoration: const InputDecoration(
                          hintText: '用户名', labelText: '用户名'),
                      // validator: (String? value) {
                      //   if (value == null || value.isEmpty) {
                      //     return '请输入用户名！';
                      //   }
                      //   return null;
                      // },
                    ),
                    const SizedBox(
                      height: 10,
                    ),
                    TextFormField(
                      controller: _passwordController,
                      obscureText: _showPassword,
                      decoration: InputDecoration(
                        labelText: '密码',
                        hintText: '密码',
                        suffixIcon: IconButton(
                            onPressed: () {
                              _changeIcon;
                            },
                            icon: Icon(_showPassword
                                ? Icons.visibility_off
                                : Icons.visibility)),
                      ),
                      // inputFormatters: [],
                      // validator: (String? value) {
                      //   if (value == null || value.isEmpty) {
                      //     return '请输入密码！';
                      //   }
                      //   return null;
                      // },
                    ),
                    TextFormField(
                      controller: _repeatPasswordController,

                      obscureText: _showPassword,
                      decoration: InputDecoration(
                          labelText: '确认密码',
                          hintText: '确认密码',
                          suffixIcon: IconButton(
                              onPressed: () {
                                _changeIcon;
                              },
                              icon: Icon(_showPassword
                                  ? Icons.visibility_off
                                  : Icons.visibility))),
                      // inputFormatters: [],
                      // validator: (String? value) {
                      //   if (value == null || value.isEmpty) {
                      //     return '请输入密码！';
                      //   } else if (value != _passwordController.text) {
                      //     return '两次输入的密码不一致';
                      //   }
                      //   return null;
                      // },
                    ),
                    Padding(
                        padding: const EdgeInsets.all(10),
                        child: SizedBox(
                          width: double.infinity,
                          child: ElevatedButton(
                              onPressed: () {
                                _submitRegister();
                              },
                              child: const Text('注册')),
                        )),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        const Text('已有帐号'),
                        TextButton(
                            onPressed: () {
                              Navigator.pushReplacementNamed(
                                  context, Routes.login);
                            },
                            child: const Text(
                              '去登录～',
                              style: TextStyle(color: Colors.green),
                            ))
                      ],
                    )
                  ],
                ))));
  }
}
